<?php
Yii::import('application.vendors.*');
require_once 'qrcode.php';

class EventsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view', 'barcode', 'emailall'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function genRandomString() {
		$length = 32;
                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$string = '';    

		for ($p = 0; $p < $length; $p++) {
			$string .= $characters[mt_rand(0, strlen($characters)-1)];
		}

	        return $string;
	}

	public function sendQRCode($email, $firstName, $lastName, $eventName, $qrCodeURL)
	{
		Yii::import('application.extensions.phpmailer.JPhpMailer');
		$mail = new JPhpMailer;
		$mail->IsSMTP();
		$mail->Host = Yii::app()->params['smtpHost'];
		$mail->SMTPAuth = Yii::app()->params['smtpAuth'];
		$mail->Username = Yii::app()->params['smtpUsername'];
		$mail->Password = Yii::app()->params['smtpPassword'];
		$mail->SetFrom(Yii::app()->params['smtpFromEmail'], Yii::app()->params['smtpFromName']);
		$mail->Subject = 'Party Scanner QR Code For: '.$eventName;
		$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
		$mail->MsgHTML('<h1>'.$eventName.'</h1><p>' . $firstName . ',<br /> Below you will find a QR code image for our event. Please present it at the door.</p> <img src="' . $qrCodeURL . '" />');
		$mail->AddAddress($email, $firstName . ' ' . $lastName);
		$mail->Send();
	}


	public function actionEmailall($id)
	{
		$mAttendingEvent = AttendingEvent::model()->findAll("event_id=:id", array(':id'=>$id));
		$event = Events::model()->find("event_id=:eid",array(':eid'=>$id));
		
		$flashMessage = "";
		foreach ($mAttendingEvent as $mae) {
			$guest = Guests::model()->find("guest_id=:gid",array(':gid'=>$mae->guest_id));
			
			$qr = new qrcode();
			$qr->text($mae->barcode_value);
			$qrCodeURL = $qr->get_link();
			
			$this->sendQRCode($guest->email,$guest->first_name,$guest->last_name, $event->name, $qrCodeURL);
			$flashMessage .= "Sent Email to {$guest->email}<br />";
		}
		Yii::app()->user->setFlash('success', $flashMessage);
		$this->redirect(array('view','id'=>$id));
	}

	public function actionBarcode($id)
	{
		$mAttendingEvent = AttendingEvent::model()->find("id=:attending_event_id", array(':attending_event_id' => $id));
		$qr = new qrcode();
		$qr->text($mAttendingEvent->barcode_value);
		$guest = Guests::model()->find("guest_id=:gid",array(':gid'=>$mAttendingEvent->guest_id));
		$event = Events::model()->find("event_id=:eid",array(':eid'=>$mAttendingEvent->event_id));			       
					       
		$firstName = $guest->first_name;
		$lastName = $guest->last_name;
		$email = $guest->email;
		$eventName = $event->name;
		$qrCodeURL = $qr->get_link();
		
		if (isset($_POST['yt0'])) {
			$this->sendQRCode($email,$firstName,$lastName,$eventName,$qrCodeURL);	
			Yii::app()->user->setFlash('success', "Sent Email to $email");
		}
		
		$this->render('viewbarcode',array(
			'firstName'=>$firstName,
			'lastName'=>$lastName,
			'eventName'=>$eventName,
			'qrCodeURL'=>$qrCodeURL,
		));
		
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		if (isset($_POST['yt0'])) { //If Submitted Form
			$mInvitedGuests = AttendingEvent::model()->findAll('event_id=:id', array(':id'=>$id));
			//Loop through each invited guest and see if they are still checked
			foreach ($mInvitedGuests as $invitedGuest) {
				if (isset($_POST['guest'])) {
					if (empty($_POST['guest'][$invitedGuest->guest_id])) {
						$invitedGuest->delete();
					}
				} else {
					//DELETE ALL
					$invitedGuest->delete();
				}
			}
			if (isset($_POST['guest'])) {
				foreach ($_POST['guest'] as $guest_id => $value) {
					$found = false;
					foreach ($mInvitedGuests as $invitedGuest) {
						if ($invitedGuest->guest_id == $guest_id) {
							$found = true;
							break;
						}
					}
					if (!$found) {
						$randomString = '';
						do {
							$randomString = $this->genRandomString();
							$m = AttendingEvent::model()->findAll("barcode_value=:bcv", array(':bcv'=>$randomString));
						} while (count($m) > 0);
						$mAttendingEvent = new AttendingEvent;
						$mAttendingEvent->event_id = $id;
						$mAttendingEvent->guest_id = $guest_id;
						$mAttendingEvent->barcode_value = $randomString;
						$mAttendingEvent->checked_in = 0;
						$mAttendingEvent->save();
					}
				}
			}
			//Loop through each guest checked in post and see if they are in database
			//If they aren't, add row
		}
		
		
		$guests = Guests::model()->findAll(array('order'=>'first_name'));
		$guestsInvited = AttendingEvent::model()->findAll('event_id=:event_id', array(':event_id'=>$id));
		$numGuestsInvited = count($guestsInvited);
		
		$this->render('view',array(
			'numGuestsInvited'=>$numGuestsInvited,
			'guestsInvited'=>$guestsInvited,
			'guests'=>$guests,
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Events;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Events']))
		{
			$model->attributes=$_POST['Events'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->event_id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Events']))
		{
			$model->attributes=$_POST['Events'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->event_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Events');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Events('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Events']))
			$model->attributes=$_GET['Events'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Events::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='events-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
